<script lang="ts" setup>
import { useStoreDict } from '@/store/modules/dict'
import { useGetCfgDict } from '@fl/api/man-api/pricing-tool'
import { cloneDeep } from 'lodash-es'
import { computed, ref, toRefs } from 'vue'

const props = withDefaults(defineProps<{
    data?: any
    limit?: number
    resOpts?: any
}>(), {
    limit: 20,
})

const emits = defineEmits(['colBlur'])

const { data, limit, resOpts } = toRefs(props)
const { data: opts } = useGetCfgDict()
const tableRef = ref()

// TODO: 新增的规则新增公式的 选择计算项
const calcOpts = computed(() => {
    return opts.value
        ? opts.value.map((v: any) => {
            return { label: v.name, value: v.id }
        })
        : []
})

const { dicts } = useStoreDict()

const tableData = ref<any>([])

function doDel({ $index }) {
    tableData.value.splice($index, 1)
    // ElMessageBox.confirm('该操作将永久删除，是否继续?', '提示', { type: 'warning' })
    //     .then(() => {
    // ElMessage({ message: '操作成功', type: 'success' })
    // tableData.value.splice($index, 1)
    // })

    emits('colBlur', cloneDeep(tableData.value))
}

function doAdd() {
    const len = tableData.value.length
    if (len >= limit.value) {
        ElMessage.error(`最多添加${limit.value}条数据！`)
        return
    }

    let isNext = true
    // 校验上条数据 是否填写完整
    if (len) {
        const target = tableData.value[len - 1]
        if ((/^\s*$/.test(target.varName)) || !target.unitType || !target.calculationType
            || (target.calculationType === '1' && !target.calculationCategoryId)
            || (target.calculationType === '2' && !target.formulaId)
        ) {
            isNext = false
        }
    }

    if (!isNext) {
        ElMessage.error(`请填写完整第${len}条数据`)
        return
    }

    // 重复校验
    const noRepeat = new Set([...tableData.value.map((v: any) => v.varName)])
    if (tableData.value.length !== noRepeat.size) {
        ElMessage.error(`存在重复变量名`)
        return
    }

    tableData.value.push({
        calculationCategoryId: '',
        calculationCategoryName: '',
        calculationType: '',
        calculationTypeName: '',
        formulaId: '',
        formulaName: '',
        unitName: '',
        unitType: '',
        varName: '',
    })

    if (tableData.value.length > 3) {
        nextTick(() => {
            tableRef.value.setScrollTop(len * 200)
        })
    }
}

function doBlur({ row }) {
    if (row.varName === '') {
        ElMessage.error(`请输入变量名`)
        return
    }

    if (row.varName.includes(' ')) {
        ElMessage.error(`请输入非空字符`)
        return
    }

    emits('colBlur', cloneDeep(tableData.value))
}

function unitChange(val, { $index }) {
    const name = dicts.jc_zjgj_unit.find((v: any) => v.value === val)?.label ?? ''
    tableData.value[$index].unitName = name
}

// 计算类型 0 文本输入  1 计算项  2 计算结果
function typeChange(val, { $index, row }) {
    const name = dicts.jc_zjgj_type.find((v: any) => v.value === val)?.label ?? ''
    tableData.value[$index].calculationTypeName = name

    // 0 文本输入类型 清空计算项
    if (row.calculationType === '0') {
        tableData.value[$index].calculationCategoryId = ''
        tableData.value[$index].calculationCategoryName = ''
    }
}

// 计算项change
function calcChange(val, { $index }, source, key) {
    const name = source.find((v: any) => v.value === val)?.label ?? ''
    tableData.value[$index][key] = name
}

watch(data, (val: any) => {
    if (val) {
        // 公式变量回显
        tableData.value = cloneDeep(val)
        emits('colBlur', cloneDeep(tableData.value))
    }
}, {
    immediate: true,
})

defineExpose({
    tableData: tableData.value,
})
</script>

<template>
    <div class="mb-0 c-#1d2129 font-600">
        添加变量
    </div>

    <el-table ref="tableRef"
              :data="tableData"
              stripe
              style="width: 100%"
              height="200"
    >
        <el-table-column label="序号"
                         type="index"
                         width="55"
        />

        <el-table-column label="变量名"
                         width="280"
        >
            <template #header>
                <span><span class="mr-5 c-red">*</span>变量名</span>
            </template>

            <template #default="scope">
                <el-input v-model="scope.row.varName"
                          maxlength="20"
                          placeholder="请输入"
                          clearable
                          @blur="doBlur(scope)"
                />
            </template>
        </el-table-column>

        <el-table-column label="单位">
            <template #header>
                <span><span class="mr-5 c-red">*</span>单位</span>
            </template>

            <template #default="scope">
                <el-select v-model="scope.row.unitType"
                           @change="unitChange($event, scope)"
                >
                    <el-option v-for="item in dicts.jc_zjgj_unit"
                               :key="item.value"
                               :label="item.label"
                               :value="item.value"
                    />
                </el-select>
            </template>
        </el-table-column>

        <el-table-column label="类型">
            <template #header>
                <span><span class="mr-5 c-red">*</span>类型</span>
            </template>

            <template #default="scope">
                <el-select v-model="scope.row.calculationType"
                           @change="typeChange($event, scope)"
                >
                    <el-option v-for="item in dicts.jc_zjgj_type"
                               :key="item.value"
                               :label="item.label"
                               :value="item.value"
                    />
                </el-select>
            </template>
        </el-table-column>

        <el-table-column>
            <template #default="scope">
                <div v-if="scope.row.calculationType === '0'" />
                <!-- 选择计算项 -->
                <el-select v-else-if="scope.row.calculationType === '1'"
                           v-model="scope.row.calculationCategoryId"
                           :disabled="!scope.row.calculationType"
                           @change="calcChange($event, scope, calcOpts, 'calculationCategoryName')"
                >
                    <el-option v-for="(item, index) in calcOpts"
                               :key="index"
                               :label="item.label"
                               :value="item.value"
                    />
                </el-select>
                <!-- 选择计算结果 -->
                <el-select v-else
                           v-model="scope.row.formulaId"
                           :disabled="!scope.row.calculationType"
                           @change="calcChange($event, scope, resOpts, 'formulaName')"
                >
                    <el-option v-for="item in resOpts"
                               :key="item.value"
                               :label="item.label"
                               :value="item.value"
                    />
                </el-select>
            </template>
        </el-table-column>

        <el-table-column label="操作"
                         width="90"
        >
            <template #default="scope">
                <el-button link
                           @click="doDel(scope)"
                >
                    删除
                </el-button>
            </template>
        </el-table-column>
    </el-table>

    <el-button class="mt-20"
               type="primary"
               plain
               @click="doAdd"
    >
        + 新增变量
    </el-button>
</template>
